<template>
  <main>
    <div class="banner">
      <img src="@/assets/images/station_bg.jpg" alt="">
    </div>
    <p class="city" @click="changeCity">
      <i class="iconfont icon-address_icon"></i>
      {{ currentCity || selectCity || positionText }}
      <i class="iconfont icon-arrowdown-copy down" v-if="currentCity || selectCity"></i>
    </p>
    <van-loading v-if="loading"/>
    <van-empty v-else-if="!loading && error" image="error" :description="errorDesc" />
    <div class="station-card" v-for="(item, index) in stationList" :key="index" v-else>
      <img v-imgUrl="item.shop_image" alt="" class="shop">
      <div class="desc">
        <p class="name">{{ item.title }}</p>
        <p class="address">
          <i class="iconfont icon-address_icon"></i>
          {{ item.address }}
        </p>
        <p class="price-box">
          <span class="rmb price">{{ item.now_price }}</span>
          <span class="rmb delete" v-if="item.discount != '0.00' ">
            {{ item.nation_price }}
          </span>
        </p>
        <p v-if="item.discount != '0.00'">
          <span class="dec">降</span> {{ item.discount }}元/升
        </p>
      </div>
      <div class="goto">
        <p class="goto-text" @click="goWechatMap(item)">
          <span>{{ item.distance || '未知距离' }}</span>
          <span class="line">|</span>
          <b><i class="iconfont icon-daohang"></i>导航</b>
        </p>
        <van-button 
          class="default-btn"
          size="small" 
          @click="goRouter(item, 'OneKeyGas')">
          去加油
        </van-button>
      </div>
    </div>
    <!-- <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <p>刷新次数: {{ count }}</p>-->
  </main>
</template>

<script>
import {mapGetters, mapActions} from 'vuex'
import stationList from 'data/list'
import baseURL from 'api/baseUrlConfig'
import * as Api from 'api'

export default {
  data() {
    return {
      defaultShop: require('assets/images/shop2.jpg'),
      currentCity: '',
      // addressComponents: {},
      stationList: [],
      isLoading: false,
      loading: false,
      error: false,
      errorDesc: '获取定位失败',
      positionText: '定位中...',
    }
  },
  computed: {
    ...mapGetters([
      'currentPosition',
      'selectCity',
      'webinfo'
    ])
  },
  created() {
    this.$emit('showTabMenu', true);
    // 没有自己切换城市
    if (!this.selectCity) {
      this.getWXLocation()
      // this.getLoactionAddress()
    } else {
      this.getStationList()
    }
  },
  // activated() {
  //   this.$emit('showTabMenu', true);
  //   // this.getLoactionAddress()
  // },
  methods: {
    ...mapActions([
      'getStationData',
      'setCurrentPosition',
      'getSelectCity'
    ]),
    changeCity() {
      this.$router.push({name: 'CityList'})
    },
    // 下拉刷新，暂时不用
    onRefresh() {
      this.address = {}
      this.getLoactionAddress()
      setTimeout(() => {
        this.isLoading = false;
      }, 1000);
    },
    // 腾讯定位
    getWXLocation() {
      this.positionText = '定位中...'
      this.loading = true
      var geolocation = new qq.maps.Geolocation(baseURL.mapKey, "myapp");
      var options = {timeout: 8000};
      geolocation.getLocation((result) => {
        console.log(result, 'result');
        this.loading = false
        this.setCurrentPosition(result)
        this.currentCity = result.city
        // this.addressComponents = result
        this.getStationList()
      }, (error) => {
        this.loading = false
        this.error = true
        this.positionText = '定位失败（手动选择城市）'
        console.log(error, 'error');
      }, options)
    },
    // 百度定位
    // getLoactionAddress() {
    //   this.loading = true
    //   var geolocation = new BMap.Geolocation();
    //   geolocation.getCurrentPosition((r) => {
    //     //用所定位的经纬度查找所在地省市街道等信息
    //     var point = new BMap.Point(r.point.lng,r.point.lat);
    //     var gc = new BMap.Geocoder();
    //     gc.getLocation(point, (result) => {
    //       console.log(result);
    //       this.loading = false
    //       if (result.address) {
    //         this.setCurrentPosition(result)
    //         this.currentCity = result.addressComponents.city
    //         // this.setCurrentCity(result.addressComponents.city)
    //         this.addressComponents = result.addressComponents
    //         // this.getStationList(this.addressComponents.city.slice(0, 2))
    //         this.getStationList()
    //       } else {
    //         this.error = true
    //       }
    //     });      
    //   },{enableHighAccuracy: true})
    // },
    // 加载当前城市的加油站
    getStationList() {
      let params = {
        city: this.selectCity || this.currentCity || '佛山'
      }
      Api.currentCityStationList(params).then(res => {
        this.stationList = res.data
        if (!this.stationList.length) {
          this.error = true
          this.errorDesc = '当前城市无加油站'
          return
        }
        this.positonDistance()
      }).catch(() => {

      })
    },
    // 计算距离
    positonDistance() {
      this.stationList.forEach(item => {
        item.now_price = item.now_price || this.webinfo.price_0_now
        item.nation_price = item.nation_price || this.webinfo.price_0_nation
        item.original_price = item.original_price || this.webinfo.price_0_original
        item.discount = (Number(item.nation_price) - Number(item.now_price)).toFixed(2)
        let first = [this.currentPosition.lng, this.currentPosition.lat]
        let second = [item.longitude, item.latitude]
        if (this.currentPosition.city) {
          item.distance = this.GetDistance(...first, ...second)
          item.juli = this.distance(...first, ...second)
        }
      })
      // 按近距离的排序
      this.stationList.sort((a, b) => {
        return a.juli - b.juli
      })
    },
    distance(lat1,  lng1,  lat2,  lng2) {
      let radLat1 = lat1 * Math.PI / 180.0;
      let radLat2 = lat2 * Math.PI / 180.0;
      let a = radLat1 - radLat2;
      let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
      s = s * 6388.137; // EARTH_RADIUS;
      return Math.round(s * 10000);
    },
    // 计算2坐标距离
    GetDistance( lat1,  lng1,  lat2,  lng2) {
      let radLat1 = lat1 * Math.PI / 180.0;
      let radLat2 = lat2 * Math.PI / 180.0;
      let a = radLat1 - radLat2;
      let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
      let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
        Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
      s = s * 6388.137; // EARTH_RADIUS;
      s = Math.round(s * 10000) / 10000;
      if (s < 1) {
        return parseInt(s * 1000) + 'm'
      }
      return s.toFixed(2) + 'km';
    },
    goWechatMap(item) {
      window.location.href = `https://apis.map.qq.com/tools/routeplan/eword=${item.title}&epointx=${item.longitude}&epointy=${item.latitude}?referer=myapp&key=${baseURL.mapKey}`
    },
    goRouter(stationData, url) {
      this.getStationData(stationData)
      // sessionStorage.setItem('stationMap', JSON.stringify(stationData))
      this.$router.push({name: url})
    }
  }
}
</script>

<style lang="less" scoped>
main{
  background: #fff;
  padding-bottom: 60px;
}
.banner{
  width: 100%;
  height: 100px;
  overflow: hidden;
  img{
    width: 100%;
    position: relative;
    top: -40px;
  }
}
.city{
  line-height: 40px;
  padding-left: 10px;
  display: flex;
  align-items: center;
  font-size: 14px;
  background: #f3f3f3;
  i{
    font-size: 14px;
    color: #2196F3;
    margin-right: 4px;
  }
  .down{
    font-size: 24px;
    color: #555;
  }
}
.station-card{
  background: #fff;
  display: grid;
  grid-template-columns: 75px auto 105px;
  grid-template-rows: auto;
  gap: 10px;
  margin-bottom: 10px;
  padding: 10px;
  box-shadow: 2px 2px 10px #eee;
  font-size: 12px;
  .shop{
    width: 70px;
    height: 70px;
    object-fit: cover;
  }
  .desc{
    font-size: 12px;
  }
  .name{
    font-size: 15px;
    font-weight: 600;
  }
  .address{
    font-size: 12px;
    margin: 5px 0;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    i{
      font-size: 12px;
      color: #2196F3;
    }
  }
  .goto{
    text-align: right;
    font-size: 12px;
    .goto-text{
      display: flex;
      justify-content: flex-end;
      .line{
        font-size: 16px;
        padding: 0 2px;
        line-height: 18px;
      }
    }
    button{
      margin-top: 20px;
    }
  }
  .price{
    color: #FF5722;
    font-weight: bold;
    font-size: 16px;
  }
  .delete{
    text-decoration: line-through;
  }
}

.dec{
  width: 20px;
  height: 20px;
  color: #fff;
  background: #FFC107;
  border-radius: 0.04rem;
  display: inline-block;
  text-align: center;
  line-height: .4rem;
  font-size: 12px;
  transform: scale(.75);
}
.van-loading{
  background: #fff;
  padding: 30px;
  text-align: center;
}
</style>
